package cat.joronya.supermanager.team;

import java.text.NumberFormat;
import java.util.Locale;

import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.utils.ImageDownloader;

@TargetApi(16)
public class MyTeamDashboardListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>
{
	// pel Log
	private static final String TAG = "supermanager";
	
	// jornada
	protected int day;
	
	// loader id
	private static final int LIST_LOADER = 0x01;
	
	// the adapter
	private FavoritesAdapter adapter;
	
	// projection del llistat de favorites
	private static final String[] FAVORITES_PROJECTION = new String[]{
			Supermanager.Market.ID_PLAYER, 			// 0
			"m."+Supermanager.Market.CODI_PLAYER,	// 1
			Supermanager.Market.NAME,				// 2
			Supermanager.Market.NACIONALITY,		// 3
			Supermanager.Market.STATUS,				// 4
			Supermanager.Market.TEAM,				// 5
			Supermanager.Market.VS_TEAM,			// 6
			Supermanager.Market.AVERAGE,			// 7
			Supermanager.Market.PRICE,				// 8
			Supermanager.PlayerList.LIST_NAME,		// 9
			Supermanager.Market.POSITION,			// 10
			"m."+Supermanager.Market._ID, 			// 11
		};
	
	public static final String POSITION_GUARDS = "GUARD";
	public static final String POSITION_FORWARDS = "FORWARD";
	public static final String POSITION_CENTERS = "CENTER";
	
	public Drawable defaultDrawable; 
	protected ImageDownloader imageDownloader;
	
	private NumberFormat decform = null;
    private NumberFormat intform = null;
    
	public static MyTeamDashboardListFragment newInstance(int day)
	{
		MyTeamDashboardListFragment fragment = new MyTeamDashboardListFragment();
		Bundle args = new Bundle();
		args.putInt("cat.joronya.supermanager.myteams.day", day);
		fragment.setArguments(args);
		return fragment;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) 
	{
    	View view = inflater.inflate(R.layout.dashboard_list, null);
    	
    	defaultDrawable = getResources().getDrawable(R.drawable.noplayer);
    	imageDownloader = new ImageDownloader(getActivity(), Supermanager.PLAYERS, 105);
    	
    	// get day from args
    	day = getArguments().getInt("cat.joronya.supermanager.myteams.day",0);
    	
    	if( decform == null )
        {
        	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	decform.setMinimumFractionDigits(2);
        }
        if( intform == null )
        {
        	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	intform.setGroupingUsed(true);
        }
        
    	return view;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) 
    {
		super.onViewCreated(view, savedInstanceState);
		
		// create adapter instance
        adapter = new FavoritesAdapter(getActivity(), null);
        
        // set the adapter to the list
        setListAdapter(adapter);
    	
    	// initialize the loader
        getLoaderManager().initLoader(LIST_LOADER, null, this);
    }

	public class PlayerData
	{
		public String idJug;
		public String cod;
		public String name;
		public String nacionality;
		public String status;
		public String vsTeam;
		public float average;
		public int price;
		public String position;
	}
	
    /**
     * Adapter to customize easily list item layout and values.
     * @author pol
     *
     */
    class FavoritesAdapter extends CursorAdapter 
	{
    	public Drawable defaultDrawable; 
    	
		public FavoritesAdapter(Context theContext, Cursor theCursor) 
		{
			super(theContext, theCursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
			defaultDrawable = theContext.getResources().getDrawable(R.drawable.noplayer);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) 
		{
			// data
			String idJug = cursor.getString(0);
			String cod = cursor.getString(1);
			String name = cursor.getString(2);
			String nacionality = cursor.getString(3);
			String status = cursor.getString(4);
			String vsTeam = cursor.getString(6);
			float average = cursor.getFloat(7);
			int price = cursor.getInt(8);
			String position = cursor.getString(10);
			
			PlayerData playerData = new PlayerData();
			playerData.idJug = idJug;
			playerData.cod = cod;
			playerData.name = name;
			playerData.nacionality = nacionality;
			playerData.status = status;
			playerData.vsTeam = vsTeam;
			playerData.average = average;
			playerData.price = price;
			playerData.position = position;
			
			// set player name
			TextView nameView = (TextView)view.findViewById(R.id.player_name);
			nameView.setText(name);
			
			Log.d(TAG,"FavoritesAdapter bindView for player: "+name);
			
			
			// mostrem banda color amb position
			TextView positionView = (TextView)view.findViewById(R.id.position);
			// bases
			if( POSITION_GUARDS.equals(position) )
			{
				positionView.setText(R.string.market_row_position_guard);
			}
			// alers
			else if( POSITION_FORWARDS.equals(position) )
			{
				positionView.setText(R.string.market_row_position_forward);
			}
			// pivots
			else 
			{
				positionView.setText(R.string.market_row_position_center);
				
			}
			
			// set player vs team
			TextView vsTeamView = (TextView)view.findViewById(R.id.player_team_vs);
			vsTeamView.setText(vsTeam);
			
			// setejem l'avatar, la foto del jugador
			ImageView avatarView = (ImageView)view.findViewById(R.id.avatar);
			avatarView.setTag(playerData);
			imageDownloader.download(String.format(Supermanager.URL_PHOTO_PLAYER, cod), (ImageView) avatarView, defaultDrawable);
			
			// setejem a tota la fila el long click
			view.setOnLongClickListener(new OnLongClickListener()
			{
				public boolean onLongClick(View view) 
				{
					ClipData data = ClipData.newPlainText("Player", "");
					ImageView avatarView2 = (ImageView)view.findViewById(R.id.avatar);
					DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(avatarView2);
					avatarView2.startDrag(data, shadowBuilder, avatarView2, 0);
					//view.setVisibility(View.INVISIBLE);
					return true;
				}
			});
			
			// set player price
			TextView priceView = (TextView) view.findViewById(R.id.player_price);
			priceView.setText(intform.format(price)+"€");
			
			// set player average
			TextView averageView = (TextView) view.findViewById(R.id.player_average);
			averageView.setText(decform.format(average));
			
			// si te status, cal ficar stick corresponent
			View stickView = view.findViewById(R.id.stick);
			if( "lesio.png".equals(status) )
			{
				stickView.setVisibility(View.VISIBLE);
				ImageView statusView = (ImageView)stickView;
				statusView.setImageResource(R.drawable.lesio);
				statusView.bringToFront();
			}
			else if( "semafor.png".equals(status) )
			{
				stickView.setVisibility(View.VISIBLE);
				ImageView statusView = (ImageView)stickView;
				// TODO: guardar drawable de semafor
				statusView.setImageResource(R.drawable.lesio);        				
				statusView.bringToFront();
			}
			// altrament mirem si te nationality
			else
			{
				// si te nacionality, cal ficar stick corresponent
				if( "nacional.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.nacional);
					statusView.bringToFront();
				}
				else if( "extra.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.extra);        				
					statusView.bringToFront();
				}
				else
				{
					stickView.setVisibility(View.INVISIBLE);
				}
			}
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) 
		{
			// create the new view
			LayoutInflater inflater = LayoutInflater.from(context);
			RelativeLayout row = (RelativeLayout)inflater.inflate(R.layout.dashboard_row, parent, false);
			return row;
		}
	}
    
    public Loader<Cursor> onCreateLoader(int id, Bundle bundle) 
	{
    	String selectionFav = Supermanager.Market.DAY + " = ? AND "+Supermanager.PlayerList.LIST_NAME+" = ? ";
		String[] selectionArgsFav = new String[]{day+"", Supermanager.FAV_LISTNAME};
		String sortOrderFav = Supermanager.Market.POSITION+" DESC, "+Supermanager.Market.NAME+" ASC";
		
		CursorLoader cursorLoader = new CursorLoader(getActivity(),
				Supermanager.Market.CONTENT_URI, 
				FAVORITES_PROJECTION, 
				selectionFav, 
				selectionArgsFav, 
				sortOrderFav);
	    return cursorLoader;
	}

	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
	{
		adapter.swapCursor(cursor);
	}

	public void onLoaderReset(Loader<Cursor> loader) 
	{
		adapter.swapCursor(null);
	}
}
